package com.sw.small_world.widgets;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;

/**
 * 动态的设置LIstView的 高度，重写测量方法，解决ScrollView和ListView的冲突
 * Created by zs on 2015/12/11.
 */
public class ScrollAndListView extends ListView {
    public ScrollAndListView(Context context) {
        super(context);
    }

    public ScrollAndListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ScrollAndListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if(this == null) return;

        ListAdapter listAdapter = this.getAdapter();
        if (listAdapter != null) {
            int totalHeight = 0;
            for (int i = 0; i < listAdapter.getCount(); i++) {
                View listItem = listAdapter.getView(i, null, this);
                listItem.measure(0, 0);
                totalHeight += listItem.getMeasuredHeight();
            }

            int height = totalHeight + (this.getDividerHeight() * (listAdapter.getCount() - 1));
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}
